<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8"/>
    <meta content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0"
          name="viewport">
    <title>新闻管理</title>
    <script th:src="@{/echarts/jquery-1.11.1.min.js}"></script>
    <link media="all" rel="stylesheet" th:href="@{/layui/css/layui.css}">
    <script charset="utf-8" th:src="@{/layui/layui.js}"></script>
    <style>
        body {
            margin: 10px;
            /* 去掉不必要的 text-align: center */
        }
        .demo-carousel {
            height: 200px;
            line-height: 200px;
            text-align: center;
        }
        /* 调整日期范围选择器的样式 */
        .layui-input-inline {
            width: 150px;
        }

        /* 为按钮添加右外边距 */
        button {
            margin-right: 10px;
        }

        /* 移除最后一个按钮的右外边距 */
        button:last-child {
            margin-right: 0;
        }

    </style>
</head>
<body class="childrenBody">
<!-- 模态窗：添加、修改 -->
<div id="addOrUpdateDiv" style="display: none;padding: 10px;padding-right: 5%">
    <form action="" class="layui-form" id="addOrUpdateFrm" lay-filter="addOrUpdateFrm" method="post">
        <input name="id" type="hidden" value=""> <!--隐藏Id 输入框-->

        <div class="layui-inline">
            <label class="layui-form-label">标题</label>
            <div class="layui-input-inline">
                <input class="layui-input input-radius" lay-verify="required" name="title" placeholder="请输入新闻标题"
                       type="text">
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label">内容</label>
            <div class="layui-input-inline">
                <input class="layui-input input-radius" lay-verify="required" name="content" placeholder="请输入文章内容"
                       type="text">
            </div>
        </div>

        <div class="layui-inline">
            <label class="layui-form-label">发布者</label>
            <div class="layui-input-inline">
                <input class="layui-input input-radius" lay-verify="required" name="pubulishby" placeholder="请输入发布者"
                       type="text">
            </div>
        </div>

        <div class="layui-form-item">
            <div class="layui-inline">
                <label class="layui-form-label">发布时间</label>
                <div class="layui-input-inline">
                    <input class="layui-input" id="test1" lay-verify="required" name="createTime" placeholder="yyyy-MM-dd HH:mm:ss"
                           type="text">
                </div>
            </div>
        </div>

        <div class="layui-inline" style="padding-left: 10%">
            <!--编辑按钮-->
            <button class="layui-btn layui-btn-sm layui-btn-radius layui-btn-normal"
                    lay-filter="addOrUpdateFrm" lay-submit="" type="button">
                <i class="layui-icon layui-icon-add-1"></i>确定
            </button>

            <button class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm" type="reset">
                <i class="layui-icon layui-icon-refresh"></i><span>重置</span>
            </button>
        </div>
    </form>
</div>

<div>
    <div style="padding: 10px;">
        <!-- 搜索条件 -->
        <fieldset class="layui-elem-field layui-field-title">
            <legend>搜索条件</legend>
        </fieldset>
        <form action="" class="layui-form" id="searchFrm" lay-filter="searchFrm" method="post">
            <div class="layui-inline">
                <label class="layui-form-label">新闻标题：</label>
                <div class="layui-input-inline">
                    <input class="layui-input input-radius" id="title" name="title" placeholder="请输入新闻标题"
                           type="text">
                </div>
            </div>
            <div class="layui-inline" style="padding-left: 10%">
                <button class="layui-btn layui-btn-sm layui-btn-radius" lay-filter="doSearch" lay-submit=""
                        type="button">
                    <i class="layui-icon layui-icon-search layui-icon-normal"></i>查询
                </button>
                <button class="layui-btn layui-btn-sm layui-btn-radius layui-btn-warm" lay-filter="doSearch"
                        lay-submit="" type="reset">
                    <i class="layui-icon layui-icon-refresh"></i><span>重置</span>
                </button>
            </div>
        </form>
        <br>
        <hr>
        <!-- 内容主体区域 -->
        <!-- table -->
        <table class="layui-hide" id="demo" lay-filter="test"></table>
    </div>
</div>

<!--编辑、删除javascript模块-->
<script id="barDemo" type="text/html">
    <button type="button" lay-event="update" class="layui-btn layui-btn-sm layui-btn-radius">
        <i class="layui-icon layui-icon-edit"></i>编辑
    </button>
    <button type="button" lay-event="delete" class="layui-btn layui-btn-sm layui-btn-radius layui-btn-danger">
        <i class="layui-icon layui-icon-delete"></i>删除
    </button>
</script>

<!-- 自定义模版工具栏 新增、批量删除-->
<div th:include="commonmenu :: toolbarDemo"></div>

<script>
    layui.config({
        version: '1632428048355' //为了更新 js 缓存，可忽略
    });

    var url;
    var tableIns;
    var mainIndex;

    //加载模块
    layui.use(["upload", "jquery", "util", "laydate"], function () { //亦可加载特定模块：layui.use(['layer', 'laydate', function(){
        //得到各种内置组件
        var layer = layui.layer //弹层
            , upload = layui.upload //拖拽上传
            , $ = layui.jquery
            , laypage = layui.laypage //分页
            , table = layui.table //表格
            , element = layui.element //元素操作
            , form = layui.form //表单
            , laydate = layui.laydate   // 日期选择器
            , util = layui.util

        // 日期时间选择器 test1 (检测时间)
        laydate.render({
            elem: '#test1'
            , type: 'datetime'
        });

        //监听Tab切换
        element.on('tab(demo)', function (data) {
            layer.tips('切换了 ' + data.index + '：' + this.innerHTML, this, {
                tips: 1
            });
        });

        //执行一个 table 实例
        tableIns = table.render({
            elem: '#demo'
            , url: '/news/listNews' //数据接口
            , title: '人口新闻表'
            , page: true //开启分页
            , width: 1500
            , height: "full-300"
            , toolbar: '#toolbarDemo' //开启工具栏，此处显示默认图标，可以自定义模板，详见文档
            , totalRow: false //开启合计行
            , cols: [ [ //表头
                {type: 'checkbox', fixed: 'left'}
                , {field: 'id', title: 'ID', width: 50, fixed: 'left', totalRowText: '合计：', hide: true}
                , {field: 'title', title: '标题', width: 277}
                , {field: 'content', title: '内容', width: 584}
                , {field: 'pubulishby', title: '发布者', width: 150}
                , {
                    field: 'createTime', title: '发布时间', width: 242, sort: true, templet: function (d) {
                        // 手动定义格式化时间
                        var date = new Date(d.createTime);
                        var year = date.getFullYear();
                        var month = String(date.getMonth() + 1).padStart(2, '0');
                        var day = String(date.getDate()).padStart(2, '0');
                        var hours = String(date.getHours()).padStart(2, '0');
                        var minutes = String(date.getMinutes()).padStart(2, '0');
                        var seconds = String(date.getSeconds()).padStart(2, '0');
                        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
                    }
                },
                {fixed: 'right', width: 200, align: 'center', toolbar: '#barDemo'}
            ] ]
        });

        //监听头工具栏事件 新增和批量删除
        table.on('toolbar(test)', function (obj) {
            var checkStatus = table.checkStatus(obj.config.id)
            var data = checkStatus.data; //获取选中的数据
            switch (obj.event) {
                case 'add':
                    //调出弹窗
                    openAddLayer();
                    break;

                case 'batchDelete':
                    if (data.length === 0) {
                        layer.msg('请至少选择一行');
                    } else {
                        layer.confirm('真的要删除选中的 ' + data.length + ' 条数据吗？', {
                            btn: ['删除', '取消']
                        }, function (index) {
                            // 发送批量删除请求
                            $.ajax({
                                url: '/news/batchDelete',
                                type: 'POST',
                                contentType: 'application/json',
                                data: JSON.stringify(data.map(item => item.id)),
                                success: function (res) {
                                    if (res.code === 200) {
                                        layer.msg('批量删除成功', {icon: 1});
                                        tableIns.reload(); // 刷新表格
                                    } else {
                                        layer.msg('批量删除失败：' + res.msg, {icon: 5});
                                    }
                                },
                                error: function (xhr, status, error) {
                                    layer.msg('网络请求失败，请重试', {icon: 5});
                                }
                            });
                        });
                    }
                    break;
            }
        });

        //删除和编辑    监听行工具事件
        table.on('tool(test)', function (obj) { //注：tool 是工具条事件名，test 是 table 原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                , layEvent = obj.event; //获得 lay-event 对应的值
            if (layEvent === 'update') {
                // 更新的逻辑代码
                openUpdateLayer(data)
            } else if (layEvent === 'delete') {
                layer.confirm('真的删除行么', function (index) {
                    obj.del(); //删除对应行（tr）的DOM结构
                    //向服务端发送删除指令
                    $.post("/news/deleteById", {id: obj.data.id}, function (res) {
                        if (res.code == 200) {
                            tableIns.reload({
                                where: "",
                            });
                        }
                        layer.msg(res.msg)
                    })
                    layer.close(index);
                });
            }
        });

        //打开添加弹出层
        function openAddLayer() {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
                area: ['450px', '300px'],
                title: '新增新闻信息',
                success: function () {
                    $("#addOrUpdateFrm")[0].reset();
                    url = "/news/addNews";
                }
            });
        }

        //打开修改的弹出层
        function openUpdateLayer(data) {
            mainIndex = layer.open({
                type: 1,
                content: $("#addOrUpdateDiv"),
               area: ['450px', '300px'],
                title: '编辑新闻信息',
                success: function () {
                    //清空原有的数据
                    $("#addOrUpdateFrm")[0].reset();
                    //装载新的数据
                    form.val("addOrUpdateFrm", data);
                    url = "/news/updateNews";
                }
            });
        }

        form.on("submit(addOrUpdateFrm)", function (data) {
            $.post(url, data.field, function (res) {
                if (res.code === 200) {
                    tableIns.reload();
                    layer.close(mainIndex);
                }
                layer.msg(res.msg);
            });
            return false;
        });

        //模糊查询
        form.on("submit(doSearch)", function (data) {
            tableIns.reload({
                where: data.field,
                page: {
                    curr: 1
                }
            });
            return false;
        })

        //分页
        laypage.render({
            elem: 'pageDemo' //分页容器的id
            , count: 1000 //数据总数
            , limit: 10 //每页显示的数据条数
            , skin: '#1E9FFF' //自定义选中色值
            //,layout: ['prev', 'page', 'next', 'count', 'limit', 'refresh', 'skip'] //自定义排版
            , jump: function (obj, first) {
                if (!first) {
                    layer.msg('第' + obj.curr + '页', {offset: 'b'});
                }
            }
        });

    })
</script>
</body>
</html>